
const roleData = {
    1: { name: "勇者", url: "/player" },
    2: { name: "魔王", url: "/npc" },
}


const { ccclass, property } = cc._decorator;

@ccclass
export default class Dialog extends cc.Component {

    @property(cc.Label)
    txt_name: cc.Label = null;

    @property(cc.Label)
    txt_content: cc.Label = null;

    @property(cc.Sprite)
    icon: cc.Sprite = null;

    public textData: { target: number, content: string }[] = [];

    public textIndex: number = -1;

    public strArr: string[];

    public tt: number = 0;

    onLoad() {

        cc.systemEvent.on("keydown", this.onKeyDown, this);

        window[`dialog`] = this;
    }


    init(textData: { target: number, content: string }[]): void {

        this.textData = textData;

        this.textIndex = -1;

        this.node.active = true;

        this.nextShowText();

    }

    nextShowText(): void {

        if (++this.textIndex < this.textData.length) {

            let data = roleData[this.textData[this.textIndex].target];

            this.txt_name.string = data.name;

            this.txt_content.string = "";

            this.strArr = this.textData[this.textIndex].content.split("");

            cc.loader.loadRes(data.url, cc.SpriteFrame, (err: Error, res) => {
                if (err) {
                    console.warn(err.message);
                    return;
                }
                this.icon.spriteFrame = res;
            })
        } else {
            this.onclose();
        }
    }

    update(dt): void {

        if (!this.strArr) return;

        this.tt += dt;
        if (this.tt >= 0.1) {
            if (this.strArr && this.strArr.length > 0) {
                this.txt_content.string += this.strArr.shift();
            } else {
                this.strArr = null;
            }
            this.tt = 0;
        }
    }

    onKeyDown(e: cc.Event.EventKeyboard): void {
        if (e.keyCode == cc.macro.KEY.space) {
            this.nextShowText();
        }
    }

    onclose(): void {
        this.node.active = false;
    }

    onDestroy(): void {
        cc.systemEvent.off("keydown", this.onKeyDown, this);
    }


}
